﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using chessLogic;

namespace chessView
{
    public partial class SelectForm : Form
    {
        private PGNImportParser importParser;
        public Game selectedGame;

        public SelectForm()
        {
            InitializeComponent();
        }
        public SelectForm(string _fenString)
        {
            InitializeComponent();
            this.FENVal.Text = _fenString;
            searchToFEN.Checked = true;
        }

        private void SelectForm_Load(object sender, EventArgs e)
        {
            this.gamesTableAdapter1.Fill(this.chessDataSet.games);
        }
        #region Buttons
        private void Ok_Click(object sender, EventArgs e)
        {
            if (this.dataGridView.SelectedRows.Count == 1)
            {
                selectedGame = new Game();
                setTag(selectedGame, 0);
                selectedGame.Moves = getSelectedGameMoves(0);
                this.Close();
            }
            else
            {
                DialogResult result = MessageBox.Show("Chose one game!!!");
            }
        }

        private void cancel_Click(object sender, EventArgs e)
        {
            Close();
        }

        private void LoadPGN_Click(object sender, EventArgs e)
        {
            OpenFileDialog loadPGNDialog = new OpenFileDialog();
            loadPGNDialog.Filter = "PGN Files|*.PGN";
            loadPGNDialog.Title = "Select a PGN File";
            if (loadPGNDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                importParser = new PGNImportParser(loadPGNDialog.FileName);
                backgroundWorker.RunWorkerAsync();
                this.gamesTableAdapter1.Fill(this.chessDataSet.games);
            }
        }

        private void save_Click(object sender, EventArgs e)
        {
            if (this.dataGridView.SelectedRows.Count != 0)
            {
                SaveFileDialog dialog = new SaveFileDialog();
                dialog.Filter = "PGN Files|*.PGN";
                if (dialog.ShowDialog() == DialogResult.OK)
                {
                    PGNExportParser export = new PGNExportParser();
                    List<Game> games = new List<Game>();
                    for (int i = 0; i < this.dataGridView.SelectedRows.Count; i++)
                    {
                        Game game = new Game();
                        setTag(game, i);
                        game.Moves = getSelectedGameMoves(i);
                        games.Add(game);
                    }
                    export.WriteFile(dialog.FileName, games);
                }
            }
            else
            {
                DialogResult result = MessageBox.Show("Chose games!!!");
            }
        }

        private void search_Click(object sender, EventArgs e)
        {
            if (searchToFEN.Checked)
                this.gamesTableAdapter1.FillByFEN(this.chessDataSet.games, FENVal.Text);
            else if(searchToallPars.Checked)
            {
                string eventName = eventVal.Text != "" ? "%" + eventVal.Text + "%" : "%";
                string site = siteVal.Text != "" ? "%" + siteVal.Text + "%" : "%";
                string date = dateVal.Text != "" ? "%" + dateVal.Text + "%" : "%";
                string round = roundVal.Text != "" ? "%" + roundVal.Text + "%" : "%";
                string white = whiteVal.Text != "" ? "%" + whiteVal.Text + "%" : "%";
                string black = blackVal.Text != "" ? "%" + blackVal.Text + "%" : "%";
                string result = resultVal.Text != "" ? resultVal.Text : "%";
                string eco = ecoVal.Text != "" ? "%" + ecoVal.Text + "%" : "%";
                this.gamesTableAdapter1.FillByAllPars(chessDataSet.games, eventName, site, date, round, white, black, result, eco);
            }
        }
        #endregion
        private void setTag(Game game,int gameNumber)
        {
            game.Event = getSelectedGame().Rows[gameNumber][1].ToString();
            game.Site = getSelectedGame().Rows[gameNumber][2].ToString();
            game.Date = getSelectedGame().Rows[gameNumber][3].ToString();
            game.Round = getSelectedGame().Rows[gameNumber][4].ToString();
            game.White = getSelectedGame().Rows[gameNumber][5].ToString();
            game.Black = getSelectedGame().Rows[gameNumber][6].ToString();
            game.Result = getSelectedGame().Rows[gameNumber][7].ToString();
            game.ECO = getSelectedGame().Rows[gameNumber][8].ToString();
        }
        private DataTable getSelectedGame()
        {
            if (this.dataGridView.SelectedRows.Count != 0)
            {
                DataTable table = new DataTable();
                for (int iCol = 0; iCol < this.dataGridView.Columns.Count; iCol++)
                {
                    table.Columns.Add(this.dataGridView.Columns[iCol].Name);
                }
                foreach (DataGridViewRow row in this.dataGridView.SelectedRows)
                {
                    DataRow datarw = table.NewRow();
                    for (int iCol = 0; iCol < this.dataGridView.Columns.Count; iCol++)
                    {
                        datarw[iCol] = row.Cells[iCol].Value;
                    }
                    table.Rows.Add(datarw);
                }
                return table;
            }
            return null;
        }
        private List<string> getSelectedGameMoves(int gameNumber)
        {
            if (this.dataGridView.SelectedRows.Count != 0)
            {
                DataBase db = new DataBase();
                int gameId = Int32.Parse(this.dataGridView.SelectedRows[gameNumber].Cells[0].Value.ToString());
                List<string> moves = db.GetMovesFromDataBaseByGameId(gameId);
                return moves;
            }
            return null;
        }

        private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
        {
            importParser.Parse();
            DataBase db = new DataBase();
            backgroundWorker.ReportProgress(0);
            db.InsertGames(importParser.Games);
            MessageBox.Show("Done!");
        }
        private void backgroundWorker1_ProgressChanged_1(object sender, ProgressChangedEventArgs e)
        {
            LoadPGN.Enabled = false;
            Ok.Enabled = false;
            search.Enabled = false;
            cancel.Enabled = false;
            save.Enabled = false;
            progressBarImport.Visible = true;
            progressBarImport.Maximum = 9;
            loadImport.Text = "Loading...";
            timerLoad.Enabled = true;
        }

        private void backgroundWorker1_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {
            LoadPGN.Enabled = true;
            Ok.Enabled = true;
            search.Enabled = true;
            cancel.Enabled = true;
            save.Enabled = true;
            progressBarImport.Visible = false;
            timerLoad.Enabled = false;
            loadImport.Text = "";
            this.gamesTableAdapter1.Fill(this.chessDataSet.games);
        }

        private void timerLoad_Tick(object sender, EventArgs e)
        {
            if (progressBarImport.Value == 9)
                progressBarImport.Value = 0;
            else
                progressBarImport.Value++;
        }
    }
}
